import { BStorage } from '@/utils/storage';
import { defineStore } from 'pinia';
import { listToTree } from '@/utils/router';

interface IMenuState {
	/**
	 * 原始菜单数据
	 */
	_menus: ISystem.IMenu[];
	/**
	 * 展开/收起
	 */
	_collapse: boolean;
	/**
	 * 标签页
	 */
	_tabs: ISystem.IMenu[];
	/**
	 * 当前选中的路由
	 */
	_currentMenu: ISystem.IMenu | null;
}
export const useMenuStore = defineStore('menu', {
	state: (): IMenuState => ({
		_menus: [],
		_collapse: false,
		_tabs: BStorage.get<ISystem.IMenu[]>('menu-tabs') || [],
		_currentMenu: null,
	}),
	getters: {
		menus: (state) => state._menus,
		menuTree: (state) => listToTree(state._menus, '0'),
		collapse: (state) => state._collapse,
		tabs: (state) => state._tabs,
		currentMenu: (state) => state._currentMenu,
	},
	actions: {
		setMenus(menus: ISystem.IMenu[]) {
			this._menus = menus;
		},
		setCollapse(collapse: boolean) {
			this._collapse = collapse;
		},
		addTabs(menu: ISystem.IMenu) {
			this.setCurrentMenu(menu);
			const index = this._tabs.findIndex((tab) => menu.id === tab.id);
			if (index < 0) {
				this._tabs.push(menu);
			}
			BStorage.set('menu-tabs', this._tabs);
		},
		setCurrentMenu(menu: ISystem.IMenu) {
			this._currentMenu = menu;
		},
		delTabs(menu: ISystem.IMenu): ISystem.IMenu | null {
			const tempTabs: ISystem.IMenu[] = JSON.parse(JSON.stringify(this._tabs));
			const index = tempTabs.findIndex((tab) => menu.id === tab.id);
			// 新的页面
			let tempCurrentMenu: ISystem.IMenu | null = null;
			// 删除当前正在打开的页面
			if (this._currentMenu?.id === menu.id) {
				tempCurrentMenu = JSON.parse(JSON.stringify(this._tabs[index - 1]));
			}
			if (index >= 0) {
				tempTabs.splice(index, 1);
			}
			this._tabs = tempTabs;
			BStorage.set('menu-tabs', tempTabs);
			return tempCurrentMenu;
		},
	},
});
